import { ConfigProvider, Table as AntTable, Tooltip, Typography } from "antd";
import { ReactNode, ComponentProps, Key, useMemo, useState } from "react";
import styles from "./index.module.less";
import { ColumnType, ColumnsType } from "antd/es/table";
import { UnknownText } from "../UnknownText";
import { Filter } from "./Filter";
import { CheckboxOptionType, CheckboxValueType } from "antd/es/checkbox/Group";
import MyLocalStorage from "@/utils/Mylocalstorage";
import { INDEX_COLUMN, OPERATE_COLUMN } from "@/config";

export interface TableProps
  extends Omit<ComponentProps<typeof AntTable>, "title"> {
  tableId?: string;
  defaultColumnsKeys?: CheckboxValueType[];
  title?: ReactNode;
  extra?: ReactNode;
  total?: number;
}

const showText = (text: any, tooltip = false) => {
  if (Array.isArray(text)) {
    if (tooltip && text.length === 0) {
      return null;
    }
    return <>{text.length > 0 ? text.toString() : <UnknownText />}</>;
  } else {
    if (tooltip && !text?.toString()) {
      return null;
    }
    return <>{text?.toString() ? text.toString() : <UnknownText />}</>;
  }
};

const getCheckKey = (column: ColumnType<any>) => {
  return (column.key || column.dataIndex) as CheckboxValueType;
};

const getFilterOptions = (columns?: ColumnsType<any>): CheckboxOptionType[] => {
  return (columns as ColumnType<any>[]).flatMap((column) => {
    return ![INDEX_COLUMN, OPERATE_COLUMN].includes(getCheckKey(column))
      ? [
          {
            label: column.title,
            value: getCheckKey(column),
          },
        ]
      : [];
  }) as CheckboxOptionType[];
};

const getHandleColumns = (columns?: ColumnsType<any>) => {
  return columns?.map((column) => ({
    ...column,
    render: (text, record, index) => {
      if (column?.render) {
        return column?.render?.(text, record, index);
      } else if (column?.width && column?.ellipsis) {
        return (
          <Typography.Text
            style={{ width: column?.width, minWidth: column?.minWidth || 100 }}
            ellipsis={{ tooltip: text }}
          >
            {text || <UnknownText />}
          </Typography.Text>
        );
      } else {
        return (
          <p style={{ minWidth: column?.minWidth || 100 }}>{showText(text)}</p>
        );
      }
    },
  })) as ColumnsType<any>;
};

export const Table = ({
  tableId,
  defaultColumnsKeys,
  className = "",
  title,
  extra,
  size,
  bordered,
  scroll,
  total,
  columns,
  ...restProps
}: TableProps) => {
  const FilterOptions = useMemo(() => getFilterOptions(columns), [columns]);

  const defaultCheckedList = useMemo(
    () =>
      defaultColumnsKeys
        ? getHandleColumns(
            columns?.filter(
              (item) =>
                item.key === INDEX_COLUMN ||
                item.key === OPERATE_COLUMN ||
                defaultColumnsKeys.includes(
                  getCheckKey(item as ColumnType<any>)
                )
            )
          )
        : getHandleColumns(columns),
    [columns]
  );
  const [prevDefaultCheckedList, setPrevDefaultCheckedList] =
    useState(defaultCheckedList);
  const [filterColumns, setFilterColumns] = useState(defaultCheckedList);
  if (prevDefaultCheckedList !== defaultCheckedList) {
    setPrevDefaultCheckedList(defaultCheckedList);
    setFilterColumns(defaultCheckedList);
  }

  const onFilterChange = (list: CheckboxValueType[]) => {
    !!tableId && MyLocalStorage.localstorage.setItem(tableId, list);
    if (!columns) return;
    setFilterColumns(
      getHandleColumns(
        columns.filter(
          (item) =>
            item.key === INDEX_COLUMN ||
            item.key === OPERATE_COLUMN ||
            list.includes(getCheckKey(item as ColumnType<any>))
        )
      )
    );
  };

  return (
    <ConfigProvider
    // theme={{
    //   components: {
    //     Table: {
    //       colorBorderSecondary: '#faad14'
    //     }
    //   }
    // }}
    >
      {title && (
        <div className={styles["table-header"]}>
          <div className={styles["table-header-content"]}>
            {title && (
              <>
                <div className={styles.title}>{title}</div>
                {!!total && (
                  <div>
                    共<span className={styles.number}>{total}</span>条
                  </div>
                )}
              </>
            )}
          </div>
          <div className={styles["table-header-extra"]}>
            {extra}
            <Filter
              options={FilterOptions}
              defaultCheckedList={defaultColumnsKeys ?? undefined}
              onChange={onFilterChange}
            />
          </div>
        </div>
      )}
      <AntTable
        rowKey={"id"}
        className={`${
          size === "small"
            ? styles["table-small-container"]
            : styles["table-container"]
        } ${className}`}
        size={size}
        bordered={bordered ?? size === "small"}
        scroll={{
          // x: Number(total) > 0 ? 'max-content' : '100%',
          x: "max-content",
          y: "calc(100vh - 40px - 64px - 54px - 32px - 33px)",
          ...scroll,
        }}
        columns={filterColumns as ColumnsType<any>}
        {...restProps}
      />
    </ConfigProvider>
  );
};
